package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.system.RoleNameDao;
import jsyf.oa.entity.system.RoleNameEntity;
import jsyf.oa.facade.system.RoleNameFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lenovo on 2017/12/7.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class RoleNameService implements RoleNameFacade {
    @Autowired
    private RoleNameDao dao;

    @Override
    public String save(String jsonData) {
        RoleNameEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), RoleNameEntity.class);
        if (StringUtils.isEmpty(entity.getId()) || "0".equals(entity.getId())) {
            dao.add(entity);
        } else {
            RoleNameEntity oldEntity = (RoleNameEntity) dao.getIBaseEntityById(entity.getId());
            oldEntity.setName(entity.getName());
            oldEntity.setDelFlag(entity.getDelFlag());
            oldEntity.setFrontFlag(entity.getFrontFlag());
            oldEntity.setTemplateId(entity.getTemplateId());
            oldEntity.setReportTemplateId(entity.getReportTemplateId());
            oldEntity.setSortNo(entity.getSortNo());
            dao.update(oldEntity);
        }
        return entity.getId();
    }

    @Override
    public boolean delById(String id) {
        return dao.delById(id) > 0;
    }

    @Override
    public List<JSONObject> getTreeNodes() {
        List<JSONObject> jsonList = dao.getJSONListByCondition("ORDER BY SORT_NO ", new Object[]{});
        List<JSONObject> nodeList = new ArrayList<>();

        JSONObject nodeRoot = new JSONObject();
        nodeRoot.put("id", "0");
        nodeRoot.put("pId", "-1");
        nodeRoot.put("name", "系统岗位");
        nodeRoot.put("type", "root");
        nodeRoot.put("isParent", true);
        nodeRoot.put("open", true);
        nodeList.add(nodeRoot);

        for (int i = 0; i < jsonList.size(); i++) {
            JSONObject node = jsonList.get(i);
            node.put("pId", "0");
            node.put("type", "roleName");
            nodeList.add(node);
        }
        return nodeList;
    }

    @Override
    public Boolean sort(String roleNameIds) {
        return dao.sort(roleNameIds);
    }

}
